<template>
  <div class="canvas-login">
    <el-card class="box-card">
      <div>
        <div class="title">
          BREAST&nbsp;&nbsp;CANCER&nbsp;&nbsp;RISK&nbsp;&nbsp;ANALYSIS&nbsp;&nbsp;SYSTEM
        </div>
        <el-form
          v-if="loginStyle == 1"
          :model="loginForm"
          :rules="rules"
          ref="loginForm"
          label-width="150px"
          class="demo-loginForm1"
          hide-required-asterisk
          status-icon
        >
          <el-form-item label="Phone:" prop="phone" class="labelSize">
            <el-input
              v-model="loginForm.phone"
              placeholder="user phone"
              size="large"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="Password:" prop="password" class="labelSize">
            <el-input
              prefix-icon="el-icon-lock"
              v-model="loginForm.password"
              :type="flag ? 'text' : 'password'"
              placeholder="user password"
              size="large"
            >
              <i
                slot="suffix"
                :class="[flag ? 'el-icon-minus' : 'el-icon-view']"
                autocomplete="auto"
                @click="flag = !flag"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="isLock" label="Testing:" class="labelSize">
            <slider-verify-code
              v-model="loginForm.isLock"
              @change="handlerLock"
            ></slider-verify-code>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="checked" class="rememberPosition"
              >Remember me</el-checkbox
            >
          </el-form-item>
        </el-form>
        <div v-if="loginStyle == 2">
          <el-form
            :model="smsLoginForm"
            :rules="rules1"
            ref="smsloginForm"
            label-width="80px"
            class="demo-loginForm2"
            hide-required-asterisk
            status-icon
          >
            <el-form-item label="Phone:" prop="phone" class="labelSize">
              <el-input
                v-model="smsLoginForm.phone"
                placeholder="user phone"
                size="large"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="code" label="Code:" class="labelSize">
              <el-input
                placeholder="verification code"
                v-model="smsLoginForm.code"
              >
                <el-button
                  slot="append"
                  icon="el-icon-s-promotion"
                  @click="sendCode(smsLoginForm.phone, message1)"
                  >{{ message1 }}
                </el-button>
              </el-input>
            </el-form-item>
          </el-form>
          <el-button
            type="success"
            size="small"
            style="margin-top: 3%; margin-left: 56%; margin-bottom: 4.7%"
            @click="back()"
            >BACK
          </el-button>
        </div>
        <div v-if="loginStyle == 3" class="demo-loginForm3">
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-card class="box-card1">
                <wxlogin
                  id="wxLoginForm"
                  style="display: none"
                  :appid="wechatLoginInfo.appid"
                  :scope="wechatLoginInfo.scope"
                  :redirect_uri="wechatLoginInfo.redirectUri"
                  :state="wechatLoginInfo.state"
                  :theme="'black'"
                ></wxlogin>
              </el-card>
            </el-col>
          </el-row>
          <el-button
            type="success"
            size="small"
            style="margin-top: 3%; margin-left: 51%; margin-bottom: 4.7%"
            @click="back()"
            >BACK
          </el-button>
        </div>
        <div v-if="loginStyle != 3">
          <el-row type="flex" justify="center">
            <el-col :span="9" style="font-size: large; font-weight: 600"
              >Log in Using Other Methods</el-col
            >
          </el-row>
          <br />
          <el-row type="flex" justify="center">
            <el-col :span="8">
              <el-link
                icon="el-icon-chat-line-round"
                type="primary"
                style="font-size: medium"
                @click="smsLogin()"
                >SMS
              </el-link>
              &nbsp;&nbsp;&nbsp;
              <el-link
                icon="el-icon-chat-dot-round"
                type="success"
                style="font-size: medium"
                @click="WechatLogin()"
              >
                Wechat</el-link
              >
            </el-col>
          </el-row>
          <br />
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button
                type="primary"
                @click="submitForm(loginStyle), rememberUser()"
              >
                LOGIN
              </el-button>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <el-button type="success" @click="submitRegister()"
                >REGISTER</el-button
              >
              &nbsp;&nbsp;&nbsp;&nbsp;
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
    <el-footer class="pa-3">
      <span class="caption">
        &copy; Copyright {{ new Date().getFullYear() }} , LT-BCRA MEDICINE
      </span>
    </el-footer>
  </div>
</template>

<script>
import api from "@/api/api.js";
import wxlogin from "vue-wxlogin";
import sliderVerifyCode from "@/components/slider-verify-code.vue";
import cookie from "js-cookie";
export default {
  name: "Login",
  components: {
    "slider-verify-code": sliderVerifyCode,
    wxlogin,
  },
  data() {
    const checkStatus = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("Please slide the slider to the right"));
      } else {
        callback();
      }
    };
    return {
      loginStyle: 1,
      loginForm: {
        phone: "",
        password: "",
        isLock: "",
      },
      smsLoginForm: {
        phone: "",
        code: "",
      },
      cookies: {
        id: "",
        token: "",
      },
      wechatLoginInfo: {
        redirectUri: "",
        appid: "",
        scope: "",
        state: "",
      },
      realCode: "",
      message1: "Send Code",
      countDown: "", //倒计时
      checked: true,
      flag: false,
      rules: {
        phone: [
          {
            required: true,
            message: "Please input a phone number",
            trigger: "blur",
          },
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: "Cell phone number format error",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "Please input a password",
            trigger: "blur",
          },
          {
            min: 6,
            max: 13,
            message: "The length is between 6 and 13 characters",
            trigger: "blur",
          },
        ],
        isLock: [{ required: true, validator: checkStatus, trigger: "blur" }],
      },
      rules1: {
        phone: [
          {
            required: true,
            message: "Please input a phone number",
            trigger: "blur",
          },
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: "Cell phone number format error",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    countDown(newV, oldV) {
      if (newV <= 0) {
        this.message1 = "Send Code";
      } else {
        this.message1 = "请在" + this.countDown + "秒内输入验证码";
      }
    },
  },
  mounted() {
    this.getCookie();
  },

  created() {
    let query = this.$route.query;
    console.log(query, "fsfss");
    if (query.id != undefined) {
      this.setCookies(query.id, query.token);
      this.$message({
        type: "success",
        message: "Login success",
      });
      this.$router.push("/home");
    }
  },

  methods: {
    //登录操作
    submitForm(different) {
      //通过密码登录
      if (different == 1) {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
          } else {
            console.log("滑块没拉啊傻瓜");
            return false;
          }
          api
            .login(this.loginForm.phone, this.loginForm.password)
            .then((response) => {
              if (response.code == "200") {
                this.$message({
                  type: "success",
                  message: "Login success",
                });
                this.setCookies(
                  response.body.information.id,
                  response.body.token
                );
                this.$router.push("/home"); //因为路由跳转前进行了配置，所以需要写在设置token后面
              }
              if (response.code == 209) {
                this.$message({
                  type: "error",
                  message: "password error",
                });
              }
              if (response.code == 208) {
                this.$message({
                  type: "error",
                  message: "account does not exist",
                });
              }
              if (response.code == 210) {
                this.$message({
                  type: "warning",
                  message:
                    "the account has been frozen,please contact the administrator",
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        });
      }
      //通过手机号发送验证码进行登录
      if (different == 2) {
        if (this.realCode == this.smsLoginForm.code && this.realCode != "") {
          this.setCookies(this.cookies.id, this.cookies.token);
          this.$message({
            type: "success",
            message: "Login success",
          });
          this.$router.push("/home"); //因为路由跳转前进行了配置，所以需要写在设置token后面
        } else {
          this.$message({
            type: "error",
            message: "code error",
          });
        }
      }
    },

    //滑块
    handlerLock(data) {
      if (data) {
        this.$refs.loginForm.validateField(this.loginForm.isLock);
      }
    },
    smsLogin() {
      this.loginStyle = 2;
    },
    //获取微信二维码
    WechatLogin() {
      api
        .getQrCode()
        .then((response) => {
          if (response.code == "200") {
            response.body.redirectUri = decodeURIComponent(
              response.body.redirectUri
            );
            this.wechatLoginInfo = response.body;
            document.getElementById("wxLoginForm").style.display = "block";
          }
        })
        .catch((error) => {});
      this.loginStyle = 3;
    },

    //生成验证码
    sendCode(value, message) {
      if ((message = "Send Code")) {
        api
          .loginBySms(value)
          .then((response) => {
            if (response.code == "200") {
              //获取到验证码
              this.realCode = response.body.code;
              this.cookies.id = response.body.information.id;
              this.cookies.token = response.body.token;
              this.timeDown();
            }
            if (response.code == 208) {
              this.$message({
                type: "error",
                message: "account does not exist",
              });
            }
            if (response.code == 210) {
              this.$message({
                type: "warning",
                message:
                  "the account has been frozen,please contact the administrator",
              });
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
    // 倒计时
    timeDown() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.countDown = TIME_COUNT;
        this.show = false;
        //定时器
        this.timer = setInterval(() => {
          if (this.countDown > 0 && this.countDown <= TIME_COUNT) {
            this.countDown--;
          } else {
            this.show = true;
            //清除定时器
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    //返回
    back() {
      this.loginStyle = 1;
    },

    //注册
    submitRegister() {
      this.$router.push("/register");
    },
    // 记住用户
    rememberUser() {
      //判断复选框是否被勾选 勾选则调用配置cookie方法
      if (this.checked == true) {
        //传入账号名，密码，和保存天数三个参数
        this.setCookie(this.loginForm.phone, this.loginForm.password, 7);
      } else {
        //清空Cookie
        this.clearCookie();
      }
    },
    //登录设置的token
    setCookies(id, token) {
      cookie.set("id", id, { domain: "localhost" });
      cookie.set("token", token, { domain: "localhost" });
    },
    //设置cookie
    setCookie(c_phone, c_pwd, exdays) {
      let exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数 7天
      //字符串拼接cookie
      window.document.cookie =
        "phone" + "=" + c_phone + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "password" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    // 读取cookie
    getCookie: function () {
      //从cooike中取值
      if (document.cookie.length > 0) {
        let arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下 cookie包含多种信息
        for (let i = 0; i < arr.length; i++) {
          let arr2 = arr[i].split("="); //再次切割 这里是name=value进行切割的
          //判断查找相对应的值
          if (arr2[0] == "phone") {
            this.loginForm.phone = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "password") {
            this.loginForm.password = arr2[1];
          }
        }
      }
      //注册后回显
      if (this.$route.params.phone && this.$route.params.password) {
        this.loginForm.phone = this.$route.params.phone;
        this.loginForm.password = this.$route.params.password;
      }
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改两个值都为空，天数为-1天就好了
    },
  },
};
</script>

<style scoped>
.canvas-login {
  background-image: url("@/assets/img/newlogin.jpg");
  background-repeat: no-repeat;
  /* 放大缩小会让图片改变 */
  background-size: cover;
  position: fixed;
  width: 100%;
  height: 100%;
}

.box-card {
  text-align: center;
  background: rgba(234, 241, 239, 0.76);
  border-radius: 20px;
  width: 40%;
  height: 60%;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.title {
  text-align: center;
  margin-top: 7%;
  font-size: 30px;
  font-weight: 600;
  color: rgb(0, 0, 0);
}

.demo-loginForm1 {
  margin-left: 13%;
  margin-top: 7%;
  width: 500px;
}

.demo-loginForm2 {
  margin-left: 13%;
  margin-top: 12%;
  width: 500px;
}

.demo-loginForm3 {
  margin-left: 1%;
  margin-top: 1%;
}

.box-card1 {
  width: 385px;
  height: 385px;
}

.rememberPosition {
  margin-left: 63%;
}
</style>
<style>
.labelSize .el-form-item__label {
  font-size: 20px;
  font-weight: 600;
  color: rgba(44, 44, 44, 0.678);
}

.pa-3 {
  margin-top: 44%;
  margin-left: 42%;
}
</style>
